<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="反馈类型" prop="feedbackType">
        <el-select v-model="queryParams.feedbackType" placeholder="请选择类型" clearable>
          <el-option label="功能建议" value="功能建议" />
          <el-option label="Bug反馈" value="Bug反馈" />
          <el-option label="内容投诉" value="内容投诉" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="processStatus">
        <el-select v-model="queryParams.processStatus" placeholder="请选择状态" clearable>
          <el-option label="待处理" :value="0" />
          <el-option label="处理中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="已关闭" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交时间" prop="feedbackTime">
        <el-date-picker clearable
          v-model="queryParams.feedbackTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:feedback:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:feedback:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:feedback:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:feedback:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="feedbackList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="feedbackId" width="80" />
      <el-table-column label="类型" align="center" prop="feedbackType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.feedbackType" size="small">{{ scope.row.feedbackType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="feedbackTitle" min-width="150" show-overflow-tooltip />
      <el-table-column label="内容" align="center" prop="feedbackContent" min-width="200" show-overflow-tooltip />
      <el-table-column label="截图" align="center" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.feedbackImages && formatImageList(scope.row.feedbackImages).length > 0" style="display: flex; justify-content: center; gap: 5px;">
            <el-image
              v-for="(img, index) in formatImageList(scope.row.feedbackImages).slice(0, 3)"
              :key="index"
              :src="img"
              :preview-src-list="formatImageList(scope.row.feedbackImages)"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
            />
            <span v-if="formatImageList(scope.row.feedbackImages).length > 3">+{{ formatImageList(scope.row.feedbackImages).length - 3 }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center" min-width="120">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <el-image
              v-if="scope.row.userAvatar"
              :src="scope.row.userAvatar"
              :preview-src-list="[scope.row.userAvatar]"
              style="width: 30px; height: 30px; border-radius: 50%; margin-right: 8px;"
              fit="cover"
            />
            <span>{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="contactInfo" min-width="120" show-overflow-tooltip />
      <el-table-column label="处理状态" align="center" prop="processStatus" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.processStatus === 0" type="info" size="small">待处理</el-tag>
          <el-tag v-else-if="scope.row.processStatus === 1" type="warning" size="small">处理中</el-tag>
          <el-tag v-else-if="scope.row.processStatus === 2" type="success" size="small">已完成</el-tag>
          <el-tag v-else-if="scope.row.processStatus === 3" type="danger" size="small">已关闭</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="processorName" width="100" />
      <el-table-column label="满意度" align="center" prop="satisfaction" width="80">
        <template slot-scope="scope">
          <el-rate v-if="scope.row.satisfaction" v-model="scope.row.satisfaction" disabled size="mini" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="feedbackTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.feedbackTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:feedback:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:feedback:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户反馈建议对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 反馈信息 -->
          <el-tab-pane label="反馈信息" name="feedback">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="反馈类型" prop="feedbackType">
                  <el-select v-model="form.feedbackType" placeholder="请选择类型" style="width: 100%">
                    <el-option label="功能建议" value="功能建议" />
                    <el-option label="Bug反馈" value="Bug反馈" />
                    <el-option label="内容投诉" value="内容投诉" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="反馈标题" prop="feedbackTitle">
                  <el-input v-model="form.feedbackTitle" placeholder="请输入反馈标题" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="反馈内容" prop="feedbackContent">
                  <el-input 
                    v-model="form.feedbackContent" 
                    type="textarea"
                    :rows="6"
                    placeholder="请输入反馈内容"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="反馈截图" prop="feedbackImages">
                  <image-upload 
                    v-model="form.feedbackImages" 
                    :limit="9"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="反馈地点" prop="feedbackLocation">
                  <el-input v-model="form.feedbackLocation" placeholder="请输入反馈地点" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="反馈坐标" prop="feedbackCoordinates">
                  <el-input v-model="form.feedbackCoordinates" placeholder="例如：经度,纬度" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="提交时间" prop="feedbackTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.feedbackTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择提交时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 分类标签 -->
          <el-tab-pane label="分类标签" name="category">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="反馈分类" prop="feedbackCategory">
                  <el-input 
                    v-model="form.feedbackCategory" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式，例如：["系统问题","用户体验"]'
                  />
                  <span class="form-tip">* 请输入合法的JSON数组格式</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="反馈标签" prop="feedbackTags">
                  <el-input 
                    v-model="form.feedbackTags" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式，例如：["紧急","高优先级"]'
                  />
                  <span class="form-tip">* 请输入合法的JSON数组格式</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 用户信息 -->
          <el-tab-pane label="用户信息" name="user">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户ID" prop="userId">
                  <el-input v-model="form.userId" placeholder="请输入用户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" placeholder="请输入用户名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="userPhone">
                  <el-input v-model="form.userPhone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式" prop="contactInfo">
                  <el-input v-model="form.contactInfo" placeholder="请输入联系方式" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用户头像" prop="userAvatar">
                  <image-upload 
                    v-model="form.userAvatar" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="APP版本" prop="appVersion">
                  <el-input v-model="form.appVersion" placeholder="请输入APP版本号" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="设备信息" prop="deviceInfo">
                  <el-input 
                    v-model="form.deviceInfo" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式的设备信息'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 处理信息 -->
          <el-tab-pane label="处理信息" name="process">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="处理状态" prop="processStatus">
                  <el-select v-model="form.processStatus" placeholder="请选择状态" style="width: 100%">
                    <el-option label="待处理" :value="0" />
                    <el-option label="处理中" :value="1" />
                    <el-option label="已完成" :value="2" />
                    <el-option label="已关闭" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理时间" prop="processTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.processTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择处理时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="处理结果" prop="processResult">
                  <el-input 
                    v-model="form.processResult" 
                    type="textarea" 
                    :rows="4"
                    placeholder="请输入处理结果说明"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理人ID" prop="processorId">
                  <el-input v-model="form.processorId" placeholder="请输入处理人ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理人姓名" prop="processorName">
                  <el-input v-model="form.processorName" placeholder="请输入处理人姓名" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 满意度评价 -->
          <el-tab-pane label="满意度评价" name="satisfaction">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="满意度评分" prop="satisfaction">
                  <el-rate v-model="form.satisfaction" show-text />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="评价意见" prop="satisfactionComment">
                  <el-input 
                    v-model="form.satisfactionComment" 
                    type="textarea" 
                    :rows="4"
                    placeholder="请输入满意度评价意见"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="反馈状态" prop="status">
                  <el-input 
                    v-model="form.status" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式，例如：{"status":"已审核","priority":"高"}'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea" 
                    :rows="5"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFeedback, getFeedback, delFeedback, addFeedback, updateFeedback } from "@/api/system/feedback";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Feedback",
  components: {
    ImageUpload
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      feedbackList: [],
      title: "",
      open: false,
      activeTab: 'feedback',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        feedbackType: null,
        feedbackTitle: null,
        feedbackContent: null,
        feedbackImages: null,
        feedbackCategory: null,
        feedbackTags: null,
        feedbackLocation: null,
        feedbackCoordinates: null,
        feedbackTime: null,
        userId: null,
        userPhone: null,
        username: null,
        userAvatar: null,
        contactInfo: null,
        appVersion: null,
        deviceInfo: null,
        processStatus: null,
        processResult: null,
        processTime: null,
        processorId: null,
        processorName: null,
        satisfaction: null,
        satisfactionComment: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        feedbackType: [
          { required: true, message: "反馈类型不能为空", trigger: "change" }
        ],
        feedbackTitle: [
          { required: true, message: "反馈标题不能为空", trigger: "blur" }
        ],
        feedbackContent: [
          { required: true, message: "反馈内容不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "反馈用户ID不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formatJsonField(jsonData) {
      if (!jsonData) return '-';
      try {
        const data = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
        if (typeof data === 'object') {
          return data.status || data.name || data.type || JSON.stringify(data);
        }
        return jsonData;
      } catch (e) {
        return jsonData;
      }
    },
    formatImageList(images) {
      if (!images) return [];
      try {
        const imageArray = typeof images === 'string' ? JSON.parse(images) : images;
        return Array.isArray(imageArray) ? imageArray : [];
      } catch (e) {
        return [];
      }
    },
    getList() {
      this.loading = true;
      listFeedback(this.queryParams).then(response => {
        this.feedbackList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        feedbackId: null,
        feedbackType: null,
        feedbackTitle: null,
        feedbackContent: null,
        feedbackImages: null,
        feedbackCategory: null,
        feedbackTags: null,
        feedbackLocation: null,
        feedbackCoordinates: null,
        feedbackTime: null,
        userId: null,
        userPhone: null,
        username: null,
        userAvatar: null,
        contactInfo: null,
        appVersion: null,
        deviceInfo: null,
        processStatus: 0,
        processResult: null,
        processTime: null,
        processorId: null,
        processorName: null,
        satisfaction: 0,
        satisfactionComment: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.feedbackId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'feedback';
      this.open = true;
      this.title = "添加用户反馈建议";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'feedback';
      const feedbackId = row.feedbackId || this.ids
      getFeedback(feedbackId).then(response => {
        this.form = response.data;
        
        // 处理图片字段
        if (this.form.feedbackImages) {
          const urls = typeof this.form.feedbackImages === 'string' 
            ? JSON.parse(this.form.feedbackImages) 
            : this.form.feedbackImages;
          this.form.feedbackImages = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        // 处理JSON字段
        const jsonFields = ['feedbackCategory', 'feedbackTags', 'deviceInfo', 'status', 'extraData'];
        for (const field of jsonFields) {
          if (this.form[field] && typeof this.form[field] === 'object') {
            this.form[field] = JSON.stringify(this.form[field], null, 2);
          }
        }
        
        this.open = true;
        this.title = "修改用户反馈建议";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理图片字段
          if (submitForm.feedbackImages && typeof submitForm.feedbackImages === 'string') {
            const urlArray = submitForm.feedbackImages.split(',').filter(url => url.trim());
            submitForm.feedbackImages = urlArray.length > 0 ? JSON.stringify(urlArray) : null;
          }
          
          // 处理JSON字段
          const jsonFields = ['feedbackCategory', 'feedbackTags', 'deviceInfo', 'status', 'extraData'];
          for (const field of jsonFields) {
            if (submitForm[field] && typeof submitForm[field] === 'string') {
              try {
                submitForm[field] = submitForm[field].trim() 
                  ? JSON.parse(submitForm[field]) 
                  : null;
              } catch (e) {
                this.$modal.msgError(`${field}字段JSON格式不正确`);
                return;
              }
            }
          }
          
          if (submitForm.feedbackId != null) {
            updateFeedback(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFeedback(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const feedbackIds = row.feedbackId || this.ids;
      this.$modal.confirm('是否确认删除用户反馈建议编号为"' + feedbackIds + '"的数据项？').then(function() {
        return delFeedback(feedbackIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/feedback/export', {
        ...this.queryParams
      }, `feedback_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
